import { fetch } from 'dva';
import { report } from './utils';

const checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    if (response && response.status) {
      const { status, statusText, url } = response;
      // 上报错误
      const obj = {
        api_url: url,
        h5url: window.location.href,
        status: status,
        status_text: statusText,
      };
      report(obj);
    }
    return response;
  }
};

const request = (url: string, options?: any) => {
  if (
    options &&
    (options.method === 'POST' ||
      options.method === 'PUT' ||
      options.method === 'DELETE')
  ) {
    if (!(options.body instanceof FormData)) {
      options.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...options.headers,
      };
      options.body = JSON.stringify(options.body);
    } else {
      options.headers = {
        Accept: 'application/json',
        ...options.headers,
      };
    }
  }

  return fetch(url, options)
    .then(checkStatus)
    .then((response) => {
      return response.json();
    })
    .catch((e) => {
      // 上报错误
      const obj = {};
      report(obj);
    });
};

export default request;
